package services

import (
	"errors"
	"stacks/database"
	"stacks/middleware"

	"gorm.io/gorm"
)

// DBWrapper 数据库操作包装器
type DBWrapper struct {
	db *gorm.DB
}

// NewDBWrapper 创建数据库包装器
func NewDBWrapper() *DBWrapper {
	return &DBWrapper{db: database.GetDB()}
}

// GetDB 获取原始数据库实例
func (w *DBWrapper) GetDB() *gorm.DB {
	return w.db
}

// First 查询单条记录，自动处理"记录不存在"错误
func (w *DBWrapper) First(dest interface{}, conds ...interface{}) error {
	err := w.db.First(dest, conds...).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		middleware.Throw(middleware.ErrNotFound)
	}
	return err
}

// Find 查询多条记录
func (w *DBWrapper) Find(dest interface{}, conds ...interface{}) error {
	return w.db.Find(dest, conds...).Error
}

// Create 创建记录
func (w *DBWrapper) Create(value interface{}) error {
	return w.db.Create(value).Error
}

// Updates 更新记录，自动处理"记录不存在"错误
func (w *DBWrapper) Updates(model interface{}, updates map[string]interface{}) error {
	result := w.db.Model(model).Updates(updates)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		middleware.Throw(middleware.ErrNotFound)
	}
	return nil
}

// Delete 删除记录，自动处理"记录不存在"错误
func (w *DBWrapper) Delete(model interface{}, conds ...interface{}) error {
	result := w.db.Delete(model, conds...)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		middleware.Throw(middleware.ErrNotFound)
	}
	return nil
}

// Count 统计记录数量
func (w *DBWrapper) Count(model interface{}, count *int64) error {
	return w.db.Model(model).Count(count).Error
}

// CheckUnique 检查字段是否唯一
func (w *DBWrapper) CheckUnique(model interface{}, field string, value interface{}, excludeID ...uint) error {
	query := w.db.Where(field+" = ?", value)

	// 如果提供了排除的ID，则排除该记录
	if len(excludeID) > 0 && excludeID[0] > 0 {
		query = query.Where("id != ?", excludeID[0])
	}

	var count int64
	err := query.Model(model).Count(&count).Error
	if err != nil {
		return err
	}

	if count > 0 {
		middleware.ThrowWithDetails(409, "资源冲突", field+"已存在")
	}

	return nil
}
